package org.zoomdev.zoom.dao.driver;

import org.zoomdev.zoom.dao.DaoException;
import org.zoomdev.zoom.dao.ddl.utils.MysqlMetaUtils;
import org.zoomdev.zoom.dao.meta.TableKeyMeta;

import java.sql.Connection;
import java.sql.SQLException;

public final class MysqlDriver extends SqlDriver {

    public static final String InnoDB = "InnoDB";
    public static final String MyISAM = "MyISAM";
    public static final String Memory = "Memory";
    public static final String NDB = "NDB";
    public static final String Archive = "Archive";
    public static final String Blackhole = "Blackhole";
    public static final String Federated = "Federated";


    public static final String CURRENT_TIMESTAMP = "CURRENT_TIMESTAMP";
    public static final String CURRENT_TIMESTAMP_ON_UPDATE = "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP";


    @Override
    public StringBuilder protectColumn(StringBuilder sb, String name) {
        int n;
        if ((n = name.indexOf(".")) > 0) {
            String table = name.substring(0, n);
            String column = name.substring(n + 1);
            protectName(sb, table).append(".");
            return protectName(sb, column);
        }
        return protectName(sb, name);
    }

    @Override
    public StringBuilder protectTable(StringBuilder sb, String name) {
        return protectName(sb, name);
    }

    @Override
    public void fill(Connection conn, TableKeyMeta tableMeta) {
        try {
            MysqlMetaUtils.fillTableMeta(conn, tableMeta);
        } catch (SQLException e) {
            throw new DaoException("获取表meta数据出错:" + tableMeta.getName(), e);
        }
    }

    private StringBuilder protectName(
            StringBuilder sb, String name
    ) {
        return sb.append('`').append(name).append("`");
    }

}
